import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import { getToken, removeToken, removeUser } from '@/utils/auth'
import store from '@/store'

// Token 相关常量
export const TokenKey = 'pet_platform_token'
export const UserKey = 'pet_platform_user'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || '',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      // 确保token不是undefined或null
      config.headers['Authorization'] = `Bearer ${token}`
      console.log('Request with token:', token)
    } else {
      console.log('No token found')
    }
    
    // 如果是FormData类型，不要覆盖Content-Type，让浏览器自动设置
    if (config.data instanceof FormData) {
      console.log('FormData detected, not setting Content-Type');
      delete config.headers['Content-Type'];
    }
    
    return config
  },
  error => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    if (res.code === 200) {
      return res
    }
    
    if (res.code === 401) {
      Message.error('登录已过期，请重新登录')
      // 清除token和用户信息
      store.dispatch('user/resetToken').then(() => {
        router.push('/login')
      })
      return Promise.reject(new Error('Unauthorized'))
    }
    
    if (res.code === 403) {
      Message.error('没有权限访问')
      return Promise.reject(new Error('Forbidden'))
    }
    
    const errorMsg = res.message || '系统错误'
    Message.error(errorMsg)
    return Promise.reject(new Error(errorMsg))
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        // 清除token和用户信息
        store.dispatch('user/resetToken').then(() => {
          router.push('/login')
        })
      }
      Message.error(error.response.data.message || '请求失败')
    } else {
      Message.error(error.message || '请求失败')
    }
    return Promise.reject(error)
  }
)

export default service 